package dao_utente;


import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;


import bean.Casa;
import bean.Utente;
import util.EntityManagerUtil;
 

public class GestoreUtente implements UtenteInterface{
    public GestoreUtente(){
    manager = EntityManagerUtil.getInstance();
    }
    @Override
    public void persist(bean.Utente p){
       EntityTransaction tn=manager.getTransaction();
       tn.begin();
       manager.persist(p);
       tn.commit();
       
    }
    @Override
    public bean.Utente findUtentebyId(Integer id_utente){
        EntityTransaction tn=manager.getTransaction();
        tn.begin();
        bean.Utente utente= manager.find(bean.Utente.class, id_utente);
        tn.commit();
        return utente;
        
        
    }
    
    @Override
	public Utente findUtente(String user, String pass) {
        bean.Utente utente= null;
    	 EntityTransaction tn=manager.getTransaction();
         tn.begin();
       Query q=manager.createQuery("SELECT u FROM Utente u WHERE u.username= ? AND u.password=?");
       q.setParameter(1, user);
       q.setParameter(2, pass);
       try{
    	   utente=(Utente)q.getSingleResult();
       }catch(NoResultException e){
    	   tn.commit();
    	   return null;
       }
      
         tn.commit();
         return utente;
	}
    
    @Override
	public boolean controllaUtente(String username, String email) {
		EntityTransaction tn=this.manager.getTransaction();
		bean.Utente utente=null;
		tn.begin();
		Query q=manager.createQuery("SELECT u FROM Utente u WHERE u.username=? OR u.email=?");
		q.setParameter(1, username);
		q.setParameter(2, email);
		 try{
			
	    	   utente=(Utente)q.getSingleResult();
	    	  
			}catch(NoResultException e){
				tn.commit();
				return false;
			}
		 catch(NonUniqueResultException n){
			
			 tn.commit();
				return true;
		 }
		 tn.commit();
		
			return true;
	
	}
    
	@Override
	public void remove(Utente u) {
		EntityTransaction tn=this.manager.getTransaction();
		tn.begin();
		try{
		Query q=manager.createQuery("DELETE Utente u where u.email = ?");
		q.setParameter(1, u.getEmail());
		q.executeUpdate();
		
		}catch(NullPointerException e){
			
		}
		tn.commit();
	}
  
   
    private EntityManager manager;















	

	
}
